<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use App\Models\Category;
use App\Models\Employ;
use App\Models\Tags;
use App\Models\TagsNews;
//use Illuminate\Http\Request;
use Illuminate\Support\Facades\Request;
use App\Models\EmployExt;
use App\User;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\Examination;

/**
 * @author Joker
 * 就业指南
 */
class EmployController extends BaseController
{
    protected $catgory;
    private $error;
    private $errMsg;
    /**
     * @see \App\Http\Controllers\Admin\BaseController::__construct()
     */
    public function __construct() {
        // TODO: Auto-generated method stub
        parent::__construct();
        $this->error = false;
        $this->catgory = Category::where(array('app'=>'employ','pid'=>0))->get();
    }


    /**
     * Show the application dashboard to the user.
     *
     * @return Response
     */
    public function index(Request $req)
    {
        if(!$this->user->can(array('viewEmploy','employ'))) abort(404);

        $data = Input::only('title','username','type','status');
        $catid = $data['type'];
        $title = $data['title'];
        $username = $data['username'];
        $status = is_null($data['status'])?4:$data['status'];
        $news = Employ::whereIn('is_validate',[1,2]);
//        if(!empty($data['title']))
//        {
//            $where['title'] = $data['title'];
//        }
//        if (!empty($data['username']))
//        {
//            $author = User::where('name','=',$data['username'])->get();
//            $where['user_id'] = $author['id'];
//        }
//        if(!empty($where))
//        {
//            $news->where($where);
//        }
//        if(!empty($data['type']))
//        {
//           $news->whereIn('cat_id',$this->getSubCategory($data['type']));
//        }


        if(!empty($title))
        {
            $news->where('title','like','%'.$title.'%');
        }
        if (!empty($username))
        {
            $authorids = User::where('name','like','%'.$username.'%')->lists('id');
            $news->whereIn('user_id',$authorids);
        }
        if(!empty($catid))
        {
            $news->whereIn('cat_id',$this->getSubCategory($catid));
        }
        if($status !='' && $status != 4)
        {
            $news->where('is_validate','=',$status);
        } else {
            $news->whereIn('is_validate',[1,2,0]);
        }
        $result = $news->orderBy('updated_at','desc')->paginate(20);

        return view('admin.employ.index')->with('news',$result)
                ->with('nowtype',$catid)
                ->with('type',$this->catgory)->with('router_a','index')
                ->with('status',$status)->with('username',$username)->with('title',$title);
    }

    /**
     * 未审核列表
     */
    public function noverify(Request $req)
    {
        if(!$this->user->can('viewEmploy')) abort(404);

        $data = Input::only('title','username','type','status');
//        $data['type'] = $data['type']?:1;
        $catid = $data['type']?:1;
        $title = $data['title'];
        $username = $data['username'];
        $status = $data['status'];

        $news = Employ::where('is_validate','=',0);
        if(!empty($title))
        {
            $news->where('title','like','%'.$title.'%');
        }
        if (!empty($username))
        {
            $authorids = User::where('name','like','%'.$username.'%')->lists('id');
            $news->whereIn('user_id',$authorids);
        }
        if(!empty($catid))
        {
            $news->whereIn('cat_id',$this->getSubCategory($catid));
        }
        if($status !='' && $status != 4)
        {
            $news->where('is_validate','=',$status);
        } else {
            $news->whereIn('is_validate',[1,2,0]);
        }


        $result = $news->orderBy('updated_at','desc')->paginate(20);
        

        return view('admin.employ.index')->with('nowtype',$catid)
            ->with('news',$result)->with('type',$this->catgory)->with('router_a','noverify')
            ->with('status',$status)->with('username',$username)->with('title',$title);
    }

    /**
     *
     * @param  $id 新闻编号
     */
    public function edit($id)
    {
        if(!$this->user->can('viewEmploy')) abort(404);

        $cateGory =array();
        $result = Employ::with('exts')->where('id','=',$id)->first();
        $newsTag = array();
        if(empty($result))
        {
            abort(404);
        }
        $exams = Examination::where('company_id','=',0)->get();
        foreach ($result->tags as $tag)
        {
            $newsTag[] = Tags::where('tags_id','=',$tag->tags_id)->first()->tags_name;
        }
        $cateGory = array();
        if(count($result->category)>0)
            $cateGory = $this->getCate($result->cat_id, $result->category->pid,"employ");
        if($result->exts->template_id == 'goodnice')
        {
            $result->content = unserialize($result->content);
            $viewPath = 'admin.employ.add';
        }
        else 
        {
            $viewPath = 'admin.employ.details';
        }
        return  view($viewPath)
                ->with('type',$this->catgory)
                ->with('result',$result)
                ->with('menuId',$result->menu_id)
                ->with('categorys',$cateGory)
                ->with('item',$this->item)
                ->with('exams',$exams)
                ->with('nowtype',Input::get('type'))
                ->with('newstag',implode(",", $newsTag));
//                 ->with('modules',$this->modules);
    }

    /**
     * @param  $id
     */
    public function show($id)
    {
        if(!$this->user->can('viewEmploy')) return $this->formatJson('false');

        $result = Employ::where('id','=',$id)->first();
        $newsTag = array();

        if(empty($result))
        {
            return $this->formatJson('false');
        }
        foreach ($result->tags as $tag)
        {
            $tags = Tags::where('tags_id','=',$tag->tags_id)->first();
            if($tags)
                $newsTag[] = $tags->tags_name;
        }
        $result->username = $result->user->name;
        $result->nowcate = $result->category->cat_name;
        $result->parentcate = count($result->category->parentCate)>0 ? $result->category->parentCate->cat_name.">":"";
        $result->topcate = count($result->category->parentCate)>0?(count($result->category->parentCate->parentCate)>0 ? $result->category->parentCate->parentCate->cat_name.">":""):"";
        $result->url = count($result->attachment)>0?$result->attachment->url:'';
        $result->newsTag = $newsTag;

        return $this->formatJson('success','获取信息成功',$result);
    }

    /**
     * 新增
     */
    public function create()
    {
        if(!$this->user->can('editEmploy')) abort(404);
        $exams = Examination::where('company_id','=',0)->get();
        $template = Input::get('template',0);
        if($template == 1)
        {
            $viewPath = 'admin.employ.add';
        }
        else 
        {
            $viewPath = 'admin.employ.details';
        }
        
        return  view($viewPath)->with('type',$this->catgory)->with('nowtype',Input::get('type'))->with('exams',$exams);
    }

    /**
     * 保存数据
     */
    public function store()
    {
        if(!$this->user->can('editEmploy')) 
            return $this->formatJson('error',$this->permerror);


        $data = Input::only(
                array(
                    'title','type','child_1','child_2','child_3','thumb','description','tagsinput','content','from','user_id','status','author','exam_id',
                    'sort','top','newsid','is_recommond','recommond_num','reading_num','template_id','content_content','content_title','to_link'
                )
            );
        if(empty($data['type']) || empty($data['child_1']) || empty($data['child_2']))
            return $this->formatJson('error','请选择分类信息！');
        $data['cat_id'] = $this->getTypes($data['type'],$data['child_1'],$data['child_2'],$data['child_3']);
        $data['to_link']=trim($data['to_link']);
        $post = array(
            'title'     => $data['title'],
            'cat_id'    => $data['cat_id'],
            'thumb'     => $data['thumb'],
            'description'=> $data['description'],
            'content'   => $data['content'],
            'from'      => $data['from'],
            'status'    => 1,
            'display_order'      => $data['sort'],
            'top'       => $data['top'],
            'is_recommond'=>$data['is_recommond'],
            'pagination_type'=>0,
            'author'        => $data['author'],
            'exam_id'   => $data['exam_id'],
            'to_link'=> $data['to_link']
        );
        $tagids = array();
        $tags = strToArray($data['tagsinput'], ",");
        foreach ($tags as $tg){
            if(!empty(trim($tg)))
            {
                $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                $tagids[] = $tagsModel->tags_id;
            }
        }
        if($data['template_id'] == 'goodnice')
        {
             $contentTitle = $data['content_title'];
             $contentContent = $data['content_content'];
             $contentInfo = array();
             for ($i=0;$i<count($contentTitle);$i++)
             {
                 $contentInfo[$i]['title'] = $contentTitle[$i];
                 $contentInfo[$i]['content']=$contentContent[$i];
             }
             $post['content'] = serialize($contentInfo);
        }
       // var_dump( $post.'21212');
        if(isset($data['newsid']) && is_numeric($data['newsid']) && $data['newsid'] > 0)
        {
            $employ = Employ::find($data['newsid']);
            foreach ($post as $key=>$val)
            {
                $employ->$key = $val;
            }
            DB::beginTransaction();
            try {
                $employ->save();
                TagsNews::where('news_id','=',$employ->id)->delete();
                foreach ($tagids as $tgd){
                    TagsNews::firstOrCreate(['tags_id'=>$tgd,'news_id'=>$employ->id]);
                }
                $this->employextinfo($employ, $data);
                DB::commit();
            }catch (\PDOException $e){
                DB::rollBack();
                Log::info(['编辑就业指南异常'=>$e->getMessage()]);
                return $this->formatJson('error','编辑失败');
            }
        }
        else
        {
            $post['user_id']     = $this->user->id;
            $post['is_validate'] = 1;
            $post['validated_at']=date('Y-m-d H:i:s');
            DB::beginTransaction();
            try {
                $employ = Employ::firstOrCreate($post);
                TagsNews::where('news_id','=',$employ->id)->delete();
                foreach ($tagids as $tgd){
                    TagsNews::firstOrCreate(['tags_id'=>$tgd,'news_id'=>$employ->id]);
                }
                $this->employextinfo($employ, $data);
                DB::commit();
            }catch (\PDOException $e){
                DB::rollBack();
                Log::info(['文章新建异常'=>$e->getMessage()]);
                return $this->formatJson('error','新建失败');
            }
        }


        return $this->formatJson('success','保存信息成功',$employ,'/admin/employ/index');
    }

    /**
     * 扩展信息
     */
    private function employextinfo($news,$data)
    {
//         $otherLink =explode(",", $data['other_link']);
        $employExt = EmployExt::find($news->id);
        if(empty($employExt))
        {
            $employExt = new EmployExt();
            $employExt->news_id = $news->id;
        }
        $employExt->reading_num = $data['reading_num'];
        $employExt->recommond_num = $data['recommond_num'];
        $employExt->other_link = 0;
        $employExt->template_id = $data['template_id'];
        $employExt->save();
    }
    
    /**
     * 就业指南审核
     */
    public function emploayValidate()
    {
        if(!$this->user->can('editEmploy'))
            return $this->formatJson('error',$this->permerror);
        
        $data = Input::only('is_validate','id');
        if(empty($data['is_validate']))
        {
            return $this->formatJson('error','请选择审核结果！');
        }
        $employ = Employ::find($data['id']);
        $employ->is_validate = $data['is_validate'];
        $employ->validated();
        if($employ->is_validate == 1)
            return $this->formatJson('success',"文章：［ ".$employ->title." ］审核通过！",$employ,'/admin/employ/noverify');
        else if($employ->is_validate == 2)
            return $this->formatJson('success',"文章：［ ".$employ->title." ］不通过！",$employ,'/admin/employ/noverify');
    }

    /**
     * 删除 就业指导文章
     */
    public function destroy($id)
    {
        if(!$this->user->can('deleteEmploy'))
            return $this->formatJson('error',$this->permerror);
        
        $news = Employ::find($id);
        $news->delete();
        return  Response::json(array('status'=>'success','msg'=>'文章：［'.$news->title.'］ 删除成功'));
    }
    
    /**
     * 首页推荐
     */
    public function recommond()
    {
        if(!$this->user->can('editEmploy'))
            return $this->formatJson('error',$this->permerror);
        
        $id = Request::input('id');
        $is_recommond = Request::input('is_disabled');
        $employ = Employ::find($id);
        
        $employ->is_recommond = $is_recommond = $is_recommond > 0 ? 0 : 1;
        if ($employ->save())
            return  Response::json(array('status'=>'success','msg'=>'广告位', 'data' => $is_recommond));
    }
    
    /**
     * 导入excel表
     */
    public function importExcel(Request $req)
    {
        if(!$this->user->can('editEmploy'))
            return $this->formatJson('error',$this->permerror);
        
        $file = Request::file('upfile');
        $base_dir = public_path('uploads/exports/employ');   
        if($file->isValid()){
            $clientName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $newName = md5(date('ymdhis').$clientName).".".$extension;
            $file->move($base_dir,$newName);
        }
        else
        {
            return $this->formatJson('error','上传文件失败！');
        }
        $file_path = public_path('uploads/exports/employ/'.$newName);
        Excel::load($file_path, function($reader)
        {
            $insert_row = array();
            $contents = array();
            foreach ($reader->noHeading()->get()->toArray() as $key=>$res)
            {
                switch ($key){
                    case 0:
                        $insert_row['title'] = $res[1];
                        break;
                    case 1:
                        $category = Category::where(['cat_name'=>trim($res[1]),'app'=>'employ'])->where('pid','>',0)->first();
                        if(empty($category))
                        {
                            $this->error = true;
                            $this->errMsg = '机构［'.$res[1].'］分类不存在，请检查后，继续上传！';
                            return false;
                        }
                        $insert_row['cat_id'] = $category->cat_id;
                        break;
                    case 2:
                        $insert_row['description'] = $res[1];
                        break;
                    case 3:
                        $insert_row['from'] = $res[1];
                        break;
                    case 4:
                        $insert_row['author'] = $res[1];
                        break;
                    case 5:
                        if(trim($res[1]) == '是')
                            $insert_row['is_recommond'] = 1;
                        else 
                            $insert_row['is_recommond'] = 0;
                        break;
                    case 6:
                        $insert_row['display_order'] =$res[1];
                        break;
                    default:
                        $contents[] = array(
                            'title'=>$res[0],
                            'content'=>str_replace("\n", "<br />", $res[1]),
                        );
                }                
                
            }
            $insert_row['thumb'] = "";
            $insert_row['content'] = serialize($contents);
            $insert_row['user_id'] = $this->user->id;
            $insert_row['status']  = 1;
            $insert_row['top']  = 0;
            $insert_row['pagination_type'] =0;
            $insert_row['is_validate'] = 1;
            $insert_row['validated_at'] = date('Y-m-d H:i:s');
            try {
                $employ = Employ::firstOrCreate($insert_row);
                $employExt = EmployExt::find($employ->id);
                if(empty($employExt))
                {
                    $employExt = new EmployExt();
                    $employExt->news_id = $employ->id;
                }
                $employExt->reading_num = 0;
                $employExt->recommond_num = 0;
                $employExt->other_link = 0;
                $employExt->template_id = 'goodnice';
                $employExt->save();
            }catch (\PDOException $e){
                Log::info(['就业指南excel上传异常'=>$e->getMessage()]);
            }
        });
        if($this->error)
        {
            return $this->formatJson('error',$this->errMsg);
        }
        return $this->formatJson('success','导入成功！');
    }
        
}